#include "unp.h"

int Write(int fd, const char* buf, int len) {
	int n = 0;
	int again = 1;
	while(again) {
		again = 0;
		if((n = write(fd, buf, len)) == -1){
			if(errno == EINTR) again = 1;
		}
	}
	return n;
}

int Read(int fd, char* buf, int len) {
	int n;
	int again = 1;
	while(again) {
		again = 0;
		if((n = read(fd, buf, len)) == -1) {
			if(errno == EINTR) again = 1;
		}
	}
	return n;
}

int Writen(int fd, const char* buf, int len) {
	int n = 0;
	int total_len = len;
	while(len > 0) {
		n = write(fd, buf, len);
		if(n < 0 && errno == EINTR) continue;
		if(n < 0 && errno != EINTR) {
			err_sys("write error");
			break;
		}
		if(n == 0) {
			err_sys("peer closed");
			break;
		}
		len -= n;
	}
	return total_len - len;
}


int Readn(int fd, char* buf, int len) {
	int n = 0;
	int total_len = 0;
	for(;;) {
		n = read(fd, buf, len);
		if(n < 0 && errno == EINTR) continue;
		if(n < 0 && errno != EINTR) {
			err_sys("read error");
			break;
		}
		if(n == 0) {
			err_sys("peer closed");
			break;
		}
		total_len += n;
		len -= n;
		buf+=n;
	}
	return total_len;
}
